<!-- 广告效果分析 -->
<template>
  <div class="ad-performance-container">

    <!-- 筛选区域 -->
    <el-card class="filter-card shadow-sm">
      <el-form :inline="true" class="demo-form-inline" style="width: max-content;">
        <el-form-item label="时间范围：">
          <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 310px;"
          />

        </el-form-item>

        <el-form-item label="广告计划：">
          <el-select v-model="filterForm.campaignId" placeholder="选择广告计划" style="width: 200px;">
            <el-option v-for="item in campaignOptions" :key="item.campaign_id" :label="item.campaign_name" :value="item.campaign_id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>总展示量</span>
          <span class="stat-trend" :class="impressionTrendClass">{{impressionTrendText}}</span>
        </div>
        <div class="stat-value">{{ totalImpressionCount || 0 }}</div>
        <div class="stat-change-desc">较上一周期{{impressionChange > 0 ? '增长' : '下降'}}{{ Math.abs(impressionChange) }}%</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>总点击量</span>
          <span class="stat-trend" :class="clickTrendClass">{{clickTrendText}}</span>
        </div>
        <div class="stat-value">{{ totalClickCount || 0 }}</div>
        <div class="stat-change-desc">较上一周期{{clickChange > 0 ? '增长' : '下降'}}{{ Math.abs(clickChange) }}%</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>总转化量</span>
          <span class="stat-trend" :class="conversionTrendClass">{{conversionTrendText}}</span>
        </div>
        <div class="stat-value">{{ totalConversionCount || 0 }}</div>
        <div class="stat-change-desc">较上一周期{{conversionChange > 0 ? '增长' : '下降'}}{{ Math.abs(conversionChange) }}%</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>总消耗</span>
          <span class="stat-trend" :class="costTrendClass">{{costTrendText}}</span>
        </div>
        <div class="stat-value">¥{{ totalCostAmount || 0 }}</div>
        <div class="stat-change-desc">较上一周期{{costChange > 0 ? '增长' : '下降'}}{{ Math.abs(costChange) }}%</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>平均点击率</span>
        </div>
        <div class="stat-value">{{ avgCtr || 0 }}%</div>
        <div class="stat-change" :class="ctrChange > 0 ? 'up' : 'down'">
          <i :class="ctrChange > 0 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          {{ ctrChange > 0 ? '+' : '' }}{{ ctrChange }}%
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>平均转化率</span>
        </div>
        <div class="stat-value">{{ avgCvr || 0 }}%</div>
        <div class="stat-change" :class="cvrChange > 0 ? 'up' : 'down'">
          <i :class="cvrChange > 0 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          {{ cvrChange > 0 ? '+' : '' }}{{ cvrChange }}%
        </div>
      </el-card>
    </div>

    <!-- 表格数据区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <span class="title">广告效果详细数据</span>
        <div class="buttons">
          <el-button type="success" @click="refreshData">刷新</el-button>
          <el-button style="float: right" type="danger" @click="deleteSelect">
            <i class="el-icon-plus"></i> 批量删除
          </el-button>
        </div>
      </div>

      <el-table
          :data="tableData"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
          style="width: 100%;">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="id" label="ID" ></el-table-column>
        <el-table-column prop="statDate" label="统计日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.statDate) }}
          </template>
        </el-table-column>
<!--        <el-table-column prop="statDate" label="统计日期" ></el-table-column>-->
<!--        <el-table-column prop="campaignName" label="广告计划"></el-table-column>-->
<!--        <el-table-column prop="title" label="广告创意" ></el-table-column>-->
<!--        <el-table-column prop="companyName" label="公司名称"></el-table-column>-->
        <el-table-column prop="impressionCount" label="展示次数"></el-table-column>
        <el-table-column prop="clickCount" label="点击次数" ></el-table-column>
        <el-table-column prop="conversionCount" label="转化次数"></el-table-column>
        <el-table-column prop="costAmount" label="消耗金额">
          <template #default="{ row }">
            ¥{{ row.costAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="ctr" label="点击率(%)" ></el-table-column>
        <el-table-column prop="cvr" label="转化率(%)" ></el-table-column>
        <el-table-column prop="cpc" label="平均点击成本" >
          <template #default="{ row }">
            ¥{{ row.cpc }}
          </template>
        </el-table-column>
        <el-table-column prop="cpm" label="千次展示成本" >
          <template #default="{ row }">
            ¥{{ row.cpm }}
          </template>
        </el-table-column>
        <el-table-column prop="cpa" label="平均转化成本" >
          <template #default="{ row }">
            ¥{{ row.cpa }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">详情</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="70%"
        center>
      <el-form :model="detailData" label-width="140px">
        <div class="grid-row">
          <el-form-item label="ID">
            <el-input v-model="detailData.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="广告主">
            <el-input v-model="detailData.companyName" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="广告计划">
            <el-input v-model="detailData.campaignName" disabled></el-input>
          </el-form-item>
          <el-form-item label="广告创意">
            <el-input v-model="detailData.title" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="统计日期">
            <el-input v-model="detailData.statDate" disabled></el-input>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-input v-model="detailData.createTime" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="展示次数">
            <el-input v-model="detailData.impressionCount" disabled></el-input>
          </el-form-item>
          <el-form-item label="点击次数">
            <el-input v-model="detailData.clickCount" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="转化次数">
            <el-input v-model="detailData.conversionCount" disabled></el-input>
          </el-form-item>
          <el-form-item label="消耗金额">
            <el-input v-model="detailData.costAmount" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="点击率">
            <el-input v-model="detailData.ctr" disabled></el-input>
          </el-form-item>
          <el-form-item label="转化率">
            <el-input v-model="detailData.cvr" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="平均点击成本">
            <el-input v-model="detailData.cpc" disabled></el-input>
          </el-form-item>
          <el-form-item label="千次展示成本">
            <el-input v-model="detailData.cpm" disabled></el-input>
          </el-form-item>
        </div>

        <div class="grid-row">
          <el-form-item label="平均转化成本">
            <el-input v-model="detailData.cpa" disabled></el-input>
          </el-form-item>
        </div>

      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';
export default {
  name: 'AdPerformanceAnalysis',
  data() {
    return {
      // 搜索表单
      filterForm: {
        dateRange: [],
        campaignId: null,
      },

      // 表格数据
      tableData: [],
      currentPage: 1,
      pageSize: 3,
      total: 0,

      // 下拉选项
      campaignOptions: [],
      // 统计数据
      totalImpressionCount: 0,
      totalClickCount: 0,
      totalConversionCount: 0,
      totalCostAmount: 0,
      totalRevenue: 0, // 新增：总收益

      // 变化率数据
      impressionChange: 0,
      clickChange: 0,
      conversionChange: 0,
      costChange: 0,
      revenueChange: 0,
      ctrChange: 0,
      cvrChange: 0,
      roiChange: 0,
      cpmChange: 0,

      // 平均值数据
      avgCtr: 0,
      avgCvr: 0,
      avgCpc: 0,
      avgCpm: 0,
      avgCpa: 0,
      roi: 0,

      // 趋势文本和类名
      impressionTrendText: '',
      clickTrendText: '',
      conversionTrendText: '',
      costTrendText: '',
      revenueTrendText: '',

      impressionTrendClass: '',
      clickTrendClass: '',
      conversionTrendClass: '',
      costTrendClass: '',
      revenueTrendClass: '',

      // 详情弹窗
      dialogVisible: false,
      dialogTitle: '广告效果详情',
      detailData: {
        id: 0,
        statDate: "",
        campaignId: 0,
        creativeId: 0,
        advertiserId: 0,
        impressionCount: 0,
        clickCount: 0,
        conversionCount: 0,
        costAmount: 0,
        revenue: 0, // 新增：收益
        ctr: 0,
        cvr: 0,
        cpc: 0,
        cpm: 0,
        cpa: 0,
        roi: 0,
        createTime: "",
        campaignName: "",
        title: "",
        companyName: ""
      },
      multipleSelection: [],
      // 上一周期数据（实际项目中应从API获取）
      previousPeriodData: {
        totalImpressionCount: 0,
        totalClickCount: 0,
        totalConversionCount: 0,
        totalCostAmount: 0,
        totalRevenue: 0,
        avgCtr: 0,
        avgCvr: 0,
        avgCpm: 0
      }
    };
  },

  mounted() {
    this.fetchTableData();
    this.loadCampaigns()
  },

  methods: {
    //广告计划
    loadCampaigns() {
      try {
        axios.get('/adCampaigns/dropdown').then(response =>{
          if (response.data.code === 200) {
            this.campaignOptions = response.data.data;
          } else {
            this.$message.error('获取广告计划列表失败');
          }
        })
      } catch (error) {
        this.$message.error('网络异常，获取广告计划列表失败');
      }
    },

    // 获取表格数据
    fetchTableData() {
      // 模拟API请求
      axios.get('/adPerDaily/page', {
        params: {
          ...(this.filterForm.dateRange && this.filterForm.dateRange.length === 2 && {
            startTime: this.filterForm.dateRange[0],
            endTime: this.filterForm.dateRange[1]
          }),
          campaignId: this.filterForm.campaignId,
          current: this.currentPage,
          size: this.pageSize
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.tableData = response.data.data.records;
          this.total = response.data.data.total;
          this.calculateStatistics();
        } else {
          this.$message.error(response.data.message || '获取列表失败');
        }
      })
    },

    // 计算统计数据
    calculateStatistics() {
      // 计算总和
      this.totalImpressionCount = this.tableData.reduce((sum, item) => sum + item.impressionCount, 0);
      this.totalClickCount = this.tableData.reduce((sum, item) => sum + item.clickCount, 0);
      this.totalConversionCount = this.tableData.reduce((sum, item) => sum + item.conversionCount, 0);
      this.totalCostAmount = this.tableData.reduce((sum, item) => sum + item.costAmount, 0).toFixed(2);
      this.totalRevenue = this.tableData.reduce((sum, item) => sum + (item.revenue || 0), 0).toFixed(2); // 新增：计算总收益

      // 计算平均值
      this.avgCtr = this.totalImpressionCount > 0 ?
          (this.totalClickCount / this.totalImpressionCount * 100).toFixed(2) : 0;
      this.avgCvr = this.totalClickCount > 0 ?
          (this.totalConversionCount / this.totalClickCount * 100).toFixed(2) : 0;
      this.avgCpc = this.totalClickCount > 0 ?
          (this.totalCostAmount / this.totalClickCount).toFixed(2) : 0;
      this.avgCpm = this.totalImpressionCount > 0 ?
          (this.totalCostAmount / this.totalImpressionCount * 1000).toFixed(2) : 0;
      this.avgCpa = this.totalConversionCount > 0 ?
          (this.totalCostAmount / this.totalConversionCount).toFixed(2) : 0;
      this.roi = this.totalCostAmount > 0 ?
          ((this.totalRevenue - this.totalCostAmount) / this.totalCostAmount * 100).toFixed(2) : 0;

      // 计算变化率（实际项目中应使用API获取的上一周期数据）
      // 这里使用模拟数据，假设上一周期数据为当前数据的80%-120%
      this.previousPeriodData.totalImpressionCount = this.totalImpressionCount * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.totalClickCount = this.totalClickCount * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.totalConversionCount = this.totalConversionCount * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.totalCostAmount = this.totalCostAmount * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.totalRevenue = this.totalRevenue * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.avgCtr = this.avgCtr * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.avgCvr = this.avgCvr * (0.8 + Math.random() * 0.4);
      this.previousPeriodData.avgCpm = this.avgCpm * (0.8 + Math.random() * 0.4);

      // 计算各项指标的变化率
      this.impressionChange = this.calculateChangeRate(this.totalImpressionCount, this.previousPeriodData.totalImpressionCount);
      this.clickChange = this.calculateChangeRate(this.totalClickCount, this.previousPeriodData.totalClickCount);
      this.conversionChange = this.calculateChangeRate(this.totalConversionCount, this.previousPeriodData.totalConversionCount);
      this.costChange = this.calculateChangeRate(this.totalCostAmount, this.previousPeriodData.totalCostAmount);
      this.revenueChange = this.calculateChangeRate(this.totalRevenue, this.previousPeriodData.totalRevenue);
      this.ctrChange = this.calculateChangeRate(this.avgCtr, this.previousPeriodData.avgCtr);
      this.cvrChange = this.calculateChangeRate(this.avgCvr, this.previousPeriodData.avgCvr);
      this.roiChange = this.calculateChangeRate(this.roi, 0); // 假设上一周期ROI为0，首次计算
      this.cpmChange = this.calculateChangeRate(this.avgCpm, this.previousPeriodData.avgCpm);

      // 设置趋势文本和类名
      this.setTrendTextAndClass('impression');
      this.setTrendTextAndClass('click');
      this.setTrendTextAndClass('conversion');
      this.setTrendTextAndClass('cost');
      this.setTrendTextAndClass('revenue');
    },

    // 计算变化率的工具方法
    calculateChangeRate(current, previous) {
      if (previous === 0) return 0;
      return ((current - previous) / previous * 100).toFixed(2);
    },

    // 设置趋势文本和类名的工具方法
    setTrendTextAndClass(metric) {
      const change = this[`${metric}Change`];
      const textKey = `${metric}TrendText`;
      const classKey = `${metric}TrendClass`;

      if (change > 0) {
        this[textKey] = `↑ 增长${change}%`;
        this[classKey] = 'trend-up';
      } else if (change < 0) {
        this[textKey] = `↓ 下降${Math.abs(change)}%`;
        this[classKey] = 'trend-down';
      } else {
        this[textKey] = '→ 持平';
        this[classKey] = 'trend-flat';
      }
    },

    // 搜索按钮点击事件
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 重置按钮点击事件
    handleReset() {
      this.filterForm = {
        dateRange: [],
        campaignId: null,
      };
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchTableData();
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchTableData();
    },

    // 表格行点击事件
    handleRowClick(row) {
      this.handleDetail(row);
    },

    // 查看详情
    handleDetail(row) {
      this.detailData = { ...row };
      this.dialogVisible = true;
    },

    // 刷新数据
    refreshData() {
      this.fetchTableData();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },

    // 批量删除
    deleteSelect(){
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录');
        return;
      }

      const ids = this.multipleSelection.map(item => item.id);

      this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 条记录吗？`, '批量删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端批量删除接口
        axios.post('/adPerDaily/deleteSelect', ids).then(response => {
          if (response.data.code === 200) {
            this.$message.success(`成功删除 ${this.multipleSelection.length} 条记录`);
            this.multipleSelection = [];
            this.fetchTableData();
          } else {
            this.$message.error(response.data.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败: ' + (error.response?.data?.message || error.message));
        })
      }).catch(() => {
        this.$message.info('删除操作已取消');
      });
    },
    // 根据id删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/adPerDaily/delete',{
          params:{
            id: row.id
          }
        }).then( () =>{
          const index = this.tableData.findIndex(item => item.id === row.id)
          if (index !== -1) {
            this.tableData.splice(index, 1)
            this.total --
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>

<style scoped>
.ad-performance-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
.filter-card{
  margin-bottom: 20px;
}

.header-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 14px;
  color: #606266;
}

.stat-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 20px;
}

.stat-card {
  width: calc(12.5% - 14px);
  min-width: 180px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

@media (max-width: 1600px) {
  .stat-card {
    width: calc(25% - 10px);
  }
}

@media (max-width: 1200px) {
  .stat-card {
    width: calc(33.33% - 10px);
  }
}

@media (max-width: 768px) {
  .stat-card {
    width: 100%;
  }
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
}

.stat-change, .stat-change-desc {
  font-size: 14px;
}

.stat-trend {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.trend-up {
  color: #67c23a;
  background-color: #f0f9eb;
}

.trend-down {
  color: #f56c6c;
  background-color: #fef0f0;
}

.trend-flat {
  color: #909399;
  background-color: #f5f7fa;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-placeholder {
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
}

.grid-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.table-card {
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.buttons {
  display: flex;
  gap: 10px;
}
</style>
